import os

from dotenv import load_dotenv
from fastapi import APIRouter,Depends,Query,Form,HTTPException,File,UploadFile

from sqlalchemy.orm import Session
from ..database.db import get_db

from ..crud.textbook_crud import (get_textbook_page_subject,get_textbook_page_grade,
                                get_textbook_page_subject_grade,
                                get_textbook_by_id,delete_textbook as delete_textbook_db,
                                update_textbook as update_textbook_db,
                                create_textbook as create_textbook_db)
from ..schemas.base import ResponseModel

from pydantic import BaseModel
from enum import Enum
from typing import List, Dict, Any
from ..utils.jwt_handler import get_username

textbook_router=APIRouter(prefix="/textbook-operate", tags=["课本"])

load_dotenv()
SOURCES_PATH = os.getenv("SOURCES_PATH")


class TextbookBase(BaseModel):
    id:int
    name: str
    path: str
    type: str
    subject: str
    grade: str
    cover: str
    starts: int
    oss_url: str
class QueryResponseModel(BaseModel):
    textbooks: List[TextbookBase]# 修改为字典类型

class TextbookList(ResponseModel):
    data: QueryResponseModel
class SubjectEnum(str, Enum):
    chinese = "语文"
    math = "数学"
    english = "英语"
    physics = "物理"
    chemistry = "化学"
    biology = "生物"
    history = "历史"
    geography = "地理"
    politics = "政治"
@textbook_router.get("/subject/{subject}",response_model=TextbookList)
async def get_textbooks_by_subject(
    subject: SubjectEnum,
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """
    根据学科分页获取教材列表
    """
    textbooks = get_textbook_page_subject(db, subject, page, page_size)
    textbooks = [textbook.as_dict() for textbook in textbooks]
    return {
        "code":200,
        "message":"ok",
        "data":{
            "textbooks":textbooks
        }
    }

class GradeEnum(str, Enum):
    seventh_grade="七年级",
    eighth_grade="八年级",
    ninth_grade="九年级"

@textbook_router.get("/grade/{grade}",response_model=TextbookList)
async def get_textbooks_by_grade(
    grade: GradeEnum,
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """
    根据年级分页获取教材列表
    """
    textbooks = get_textbook_page_grade(db, grade, page, page_size)
    textbooks = [textbook.as_dict() for textbook in textbooks]
    return {
        "code":200,
        "message":"ok",
        "data":{
            "textbooks":textbooks
        }
    }

@textbook_router.get("/grade/{grade}/subject/{subject}",response_model=TextbookList)
async def get_textbooks_by_grade_and_subject(
        grade: GradeEnum,
        subject: SubjectEnum,
        page: int = Query(1, ge=1),
        page_size: int = Query(10, ge=1, le=100),
        db: Session = Depends(get_db)
):
    """
    根据年级和学科分页获取教材列表
    """
    textbooks = get_textbook_page_subject_grade(db, subject, grade, page, page_size)
    textbooks = [textbook.as_dict() for textbook in textbooks]
    return {
        "code":200,
        "message":"ok",
        "data":{
            "textbooks":textbooks
        }
    }

class TextbookDemo(BaseModel):
    textbook: TextbookBase
class TextbookResponseModel(ResponseModel):
    data: TextbookDemo
@textbook_router.get("/{textbook_id}",response_model=TextbookResponseModel)
async def get_textbook(textbook_id: int, db: Session = Depends(get_db)):
    textbook=get_textbook_by_id(db,textbook_id)
    return {
        "code":200,
        "message":"ok",
        "data":{
            "textbook":textbook
        }
    }

@textbook_router.post("/textbooks", response_model=TextbookResponseModel)
async def create_textbook(subject: SubjectEnum, grade: GradeEnum,textbook_file:UploadFile=File(...),
                          db: Session = Depends(get_db),
                          username: str = Depends(get_username)
                          ):
    """
    创建一个新的课本。

    **课本必须为pdf文件**
    - param textbook: 要创建的课本信息
    - return: 创建的课本信息
    """
    if not textbook_file.filename.lower().endswith('.pdf'):
        raise HTTPException(status_code=400, detail="文件格式错误")
    # 由于TextbookBase不包含id，我们需要将数据转换为create_textbook函数需要的参数
    base_path = "sources/textbooks/download"
    print(subject)
    subject_folder = f"初中{subject.value}"

    file_path_db = base_path+"/"+subject_folder+"/"+textbook_file.filename
    download_path=os.path.join(SOURCES_PATH, file_path_db)
    # 确保目录存在
    os.makedirs(os.path.dirname(download_path), exist_ok=True)

    # 保存文件
    try:
        # 读取上传的文件内容
        file_content = await textbook_file.read()

        # 写入到指定路径
        with open(download_path, "wb") as buffer:
            buffer.write(file_content)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文件保存失败: {str(e)}")

    # 重置文件指针，以便后续可能需要再次读取
    await textbook_file.seek(0)
    created_textbook = create_textbook_db(
        db,
        name=textbook_file.filename,
        path=file_path_db,
        type="textbook",
        subject=subject,
        grade=grade,
        cover="",
        starts=0,

    )
    return {
        "code": 200,
        "message": "创建课本成功",
        "data": {
            "textbook": created_textbook
        }
    }

@textbook_router.put("/{textbook_id}", response_model=TextbookResponseModel)
async def update_textbook(textbook_id: int, subject: SubjectEnum=None,
                          grade: GradeEnum=None, db: Session = Depends(get_db),
                          username: str = Depends(get_username)):
    """
    更新指定 ID 的课本信息。

    **只能更新课本的科目和年级。如果需要其他内容，需重新上传文件**

    **只更新一项时，其余项不用填写**
    - param textbook_id: 要更新的课本的 ID
    - param subject: 更新后的科目
    - param grade: 更新后的年级
    - return: 更新的课本信息
    """
    # 调用crud层的更新函数
    updated_textbook = update_textbook_db(db, textbook_id=textbook_id, subject=subject, grade=grade)
    return {
        "code": 200,
        "message": "更新成功",
        "data": {
            "textbook": updated_textbook
        }
    }


@textbook_router.delete("/{textbook_id}", response_model=TextbookResponseModel)
async def delete_textbook(textbook_id: int, db: Session = Depends(get_db),
                          username: str = Depends(get_username)):
    """
    删除指定 ID 的课本。

    - param textbook_id: 要删除的课本的 ID
    - return: 删除的课本信息
    """
    # 调用crud层的删除函数
    deleted_textbook = delete_textbook_db(db, textbook_id)
    return {
        "code": 200,
        "message": "删除成功",
        "data": {
            "textbook": deleted_textbook
        }
    }